import { ref, onMounted, onUnmounted, type Ref } from 'vue';
import * as echarts from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { BarChart, LineChart, PieChart,RadarChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
} from 'echarts/components';
import type { ECharts, EChartsOption, SetOptionOpts } from 'echarts';

// 注册必要的组件
echarts.use([
  CanvasRenderer,
  BarChart,
  LineChart,
  PieChart,
  RadarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
]);

interface UseEchartsReturn {
  chartInstance: Ref<ECharts | null>;
  isInitialized: Ref<boolean>;
  initChart: (options: EChartsOption) => boolean;
  updateOptions: (newOptions: EChartsOption, opts?: SetOptionOpts) => void;
  resizeChart: () => void;
  disposeChart: () => void;
  getInstance: () => ECharts | null;
}

export function useEcharts(containerRef: Ref<HTMLElement | null | undefined>): UseEchartsReturn {
  const chartInstance = ref<ECharts | null>(null);
  const isInitialized = ref(false);

  // 手动初始化图表
  const initChart = (options: EChartsOption): boolean => {
    if (!containerRef.value) {
      console.warn('Chart container not found');
      return false;
    }
    
    if (isInitialized.value) {
      console.warn('Chart already initialized');
      return false;
    }
    
    if (chartInstance.value) {
      console.warn('Chart instance already exists');
      return false;
    }

    try {
      chartInstance.value = echarts.init(containerRef.value);
      
      if (!chartInstance.value) {
        console.error('Failed to create chart instance');
        return false;
      }
      
      chartInstance.value.setOption(options);
      isInitialized.value = true;
      return true;
    } catch (error) {
      console.error('Failed to initialize chart:', error);
      return false;
    }
  };

  // 更新选项
  const updateOptions = (newOptions: EChartsOption, opts: SetOptionOpts = {}): void => {
    if (!chartInstance.value) {
      console.warn('Chart not initialized');
      return;
    }
    
    if (!isInitialized.value) {
      console.warn('Chart not initialized, cannot update options');
      return;
    }
    
    try {
      chartInstance.value.setOption(newOptions, opts);
    } catch (error) {
      console.error('Failed to update chart options:', error);
    }
  };

  // 调整大小
  const resizeChart = (): void => {
    if (!chartInstance.value || !isInitialized.value) {
      return;
    }
    
    try {
      chartInstance.value.resize();
    } catch (error) {
      console.error('Failed to resize chart:', error);
    }
  };

  // 销毁图表
  const disposeChart = (): void => {
    if (chartInstance.value && isInitialized.value) {
      try {
        chartInstance.value.dispose();
      } catch (error) {
        console.error('Failed to dispose chart:', error);
      } finally {
        chartInstance.value = null;
        isInitialized.value = false;
      }
    }
  };

  // 获取图表实例（用于调用 ECharts 原生方法）
  const getInstance = (): ECharts | null => {
    return chartInstance.value;
  };

  onMounted(() => {
    window.addEventListener('resize', resizeChart);
  });

  onUnmounted(() => {
    disposeChart();
    window.removeEventListener('resize', resizeChart);
  });

  return {
    chartInstance,
    isInitialized,
    initChart,
    updateOptions,
    resizeChart,
    disposeChart,
    getInstance,
  };
}